package com.gsoe.problem.config;

import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.spring.starter.RedissonProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {
    @Value("${redis.url}")
    private String redisUrl;
    @Value("${redis.port}")
    private int redisPort;

    @Value("${redis.password}")
    private String redisPassword;

    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate();
        //设置redis的连接对象
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //设置redis的序列号器
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }


    @Bean
    public RedissonClient redissonClient() throws Exception {
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://"+redisUrl+":"+redisPort)
                .setTimeout(3000);
        if(StringUtils.isNotEmpty(redisPassword))config.useSingleServer().setPassword(redisPassword);
        RedissonClient redissonClient = Redisson.create(config);
        System.out.println("Redisson 已启动");
        return redissonClient;
    }
}
